package com.jeesite.modules.sys.utils;

import com.jeesite.common.lang.DateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class WordUtils {
    private WordUtils() {
        throw new AssertionError();
    }
    public static String exportMillCertificateWord(HttpServletRequest request,String baseType,String fileName,  Map map,String ftlFile) throws IOException {
        Configuration configuration = null;
        //模板文件的位置
        String templateFolder =request.getSession().getServletContext().getRealPath("/templates");
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setDirectoryForTemplateLoading(new File(templateFolder));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHssmmSSS");
        Template freemarkerTemplate = configuration.getTemplate(ftlFile);
        File file = null;

        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map,freemarkerTemplate,baseType,fileName);
            fin = new FileInputStream(file);


            return file.getName();
        } finally {
            if(fin != null) fin.close();
            if(out != null) out.close();
        }
    }

    /**
     *
     * @param dataMap
     * @param template
     * @param baseType
     * @param fileType 文书类别
     * @return
     */
    private static File createDoc(Map<?, ?> dataMap, Template template,String baseType,String fileType) {
        String  filePath = PathUtils.getFilePath((String)dataMap.get("officeName"),baseType,(String)dataMap.get("enterpriseName"));
        String name =  filePath+ fileType  +"_" + (String)dataMap.get("enterpriseName") +"_"+ DateUtils.formatDate(new Date(),"yyyyMMddhhmmss")+".doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);

            //生成pdf项目
            Doc2Utils.doc2pdf(name);

            //生成png项目
            Doc2Utils.doc2png(name);


            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }


}
